<template>
  <van-icon
    :name="value ? 'star' : 'star-o'"
    :class="{ collected: value }"
    @click="onCollect"
    :loading="loading"
    loading-type="spinner"
  />
</template>

<script>
export default {
  name: 'CollectArticle',
  props: {
    value: {
      type: Boolean,
      required: true
    },
    articleId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      loading: false
    }
  },
  methods: {
    async onCollect() {
      this.loading = true
      try {
        if (this.value) {
          // 取消收藏
          await this.$api.deleteCollect(this.articleId)
        } else {
          // 收藏
          await this.$api.addCollect(this.articleId)
        }
        // 更新视图
        this.$emit('input', !this.value)
        // 提示信息
        this.$toast(this.value ? '取消收藏' : '收藏成功')
      } catch (err) {
        this.$toast.fail('操作失败,请稍后重试')
      }
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
.collected {
  color: #ffa500;
}
</style>
